package com.springboot.file.provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文档处理器工厂
 * 根据业务类型获取对应的处理器
 */
@Component
public class DocumentProviderFactory {
    private static final Logger log = LoggerFactory.getLogger(DocumentProviderFactory.class);
    
    private final Map<String, DocumentProvider> providerMap = new HashMap<>();
    
    @Autowired
    private List<DocumentProvider> providers;
    
    @PostConstruct
    public void init() {
        if (providers != null && !providers.isEmpty()) {
            for (DocumentProvider provider : providers) {
                String businessType = provider.getBusinessType();
                if (businessType != null && !businessType.trim().isEmpty()) {
                    providerMap.put(businessType.toUpperCase(), provider);
                    log.info("注册文档处理器: {} -> {}", businessType, provider.getClass().getSimpleName());
                }
            }
        }
    }
    
    /**
     * 根据业务类型获取对应的处理器
     *
     * @param businessType 业务类型
     * @return 文档处理器
     * @throws IllegalArgumentException 如果找不到对应的处理器
     */
    public DocumentProvider getProvider(String businessType) {
        if (businessType == null || businessType.trim().isEmpty()) {
            throw new IllegalArgumentException("业务类型不能为空");
        }
        
        DocumentProvider provider = providerMap.get(businessType.toUpperCase());
        if (provider == null) {
            throw new IllegalArgumentException("找不到业务类型[" + businessType + "]对应的文档处理器");
        }
        
        return provider;
    }
    
    /**
     * 检查是否存在指定业务类型的处理器
     *
     * @param businessType 业务类型
     * @return 是否存在
     */
    public boolean hasProvider(String businessType) {
        if (businessType == null || businessType.trim().isEmpty()) {
            return false;
        }
        
        return providerMap.containsKey(businessType.toUpperCase());
    }
} 